import React, { PureComponent } from 'react';
import { Modal, Form, Input, message } from 'antd';
import { changePwd } from '@/services/user';

const { Item: FormItem } = Form;

@Form.create()
class ChangePassword extends PureComponent {
  state = {
    visible: false,
    confirmLoading: false,
  };

  componentWillReceiveProps(nextProps) {
    const { props } = this;
    if (props.visible !== nextProps.visible) {
      this.setState({ visible: nextProps.visible });
    }
  }

  handleClose = () => {
    const { form } = this.props;
    form.resetFields();
    this.setState({ visible: false });
  };

  handleOk = () => {
    const { form } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        this.setState({ confirmLoading: true });
        changePwd(values).then(response => {
          this.setState({ confirmLoading: false });
          if (response.code === 0) {
            this.setState({ visible: false });
            message.success('修改成功');
          } else {
            message.error(response.message);
          }
        });
      }
    });
  };

  render() {
    const { visible, confirmLoading } = this.state;
    const { form } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 15 },
    };
    return (
      <Modal
        title="修改密码"
        visible={visible}
        confirmLoading={confirmLoading}
        onCancel={this.handleClose}
        onOk={this.handleOk}
      >
        <Form>
          <FormItem label="原密码" {...formItemLayout}>
            {form.getFieldDecorator('oldPassword', {
              rules: [
                {
                  type: 'string',
                  required: true,
                  message: '原密码不能为空！',
                },
              ],
            })(<Input.Password />)}
          </FormItem>
          <FormItem label="新密码" {...formItemLayout}>
            {form.getFieldDecorator('newPassword', {
              rules: [
                {
                  type: 'string',
                  required: true,
                  message: '新密码不能为空！',
                },
              ],
            })(<Input.Password />)}
          </FormItem>
        </Form>
      </Modal>
    );
  }
}

export default ChangePassword;
